package cn.com.inossem.utils;

import java.io.File;
import java.net.URL;

import org.apache.commons.io.FileUtils;

import android.content.ContentValues;
import android.content.Context;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.provider.MediaStore;
import android.text.TextUtils;
import android.util.Log;
import android.widget.Toast;
import cn.com.inossem.activity.R;
import cn.com.inossem.config.WSConfig;
import cn.com.inossem.utils.AsyncImageLoader.ImageCallback;

public class AsyncImageSaver {
	public Context context;

	public AsyncImageSaver(Context context) {
		this.context = context;
	}

	public Drawable loadDrawable(final String filename,
			final ImageCallback imageCallback) {
		final Handler handler = new Handler() {
			public void handleMessage(Message message) {
				imageCallback.imageLoaded((Drawable) message.obj, filename);
			}
		};
		new Thread() {
			@Override
			public void run() {
				savePicture(filename);
				Message message = handler.obtainMessage(0, null);
				handler.sendMessage(message);
			}
		}.start();
		return null;
	}

	// 保存图片
    public void savePicture(String filename) {
        if (TextUtils.isEmpty(filename)) {
            return;
        }
        String path = WSConfig.IMAGE_URL + filename;
        String picPath = getSystemImagePath();
        String dstPath = picPath + filename;
            try {
            	URL httpurl = new URL(path);   
            	File f1 = new File(picPath);  
            	if (!f1.exists())
            		f1.mkdirs();
                File f = new File(dstPath);   
                f.createNewFile();
                FileUtils.copyURLToFile(httpurl, f);   
                ContentValues values = new ContentValues(2);
                values.put(MediaStore.Images.Media.MIME_TYPE, "image/jpeg");
                values.put(MediaStore.Images.Media.DATA, dstPath);
                context.getContentResolver().insert(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, values);
                Toast.makeText(context,context.getString(R.string.picture_save_to), Toast.LENGTH_LONG).show();
            } catch (Exception e) {
                // may be java.lang.UnsupportedOperationException
            	Log.i("ImageAdapter", "Cann't save image " + e.getMessage());
//                Toast.makeText(context, context.getString(R.string.picture_save_fail), Toast.LENGTH_LONG).show();
            }
    }
    
    public String getSystemImagePath() {
        if (Build.VERSION.SDK_INT > 7) {
            String picturePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES).getAbsolutePath();
            return picturePath + "/inossem/";
        } else {
            String picturePath = Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DCIM).getAbsolutePath();
            return picturePath + "/inossem/";
        }
    }
}